<?php
/**
 * Created by PhpStorm.
 * User: 元曦
 * Date: 2023-02-22
 * Time: 16:46:19
 * Info: 模型管理
 */

namespace app\admin\controller;

use app\common\controller\AdminController;
use think\facade\Db;
use think\facade\View;
use app\common\model\Models as ModelsModel;

class Models extends Base
{

    /**
     * 获取内容模型列表页
     * @return string
     */
    public function index()
    {
        $params = [];
        //判断是否是ajax发送方式
        if ($this->request->isAjax()) {
            $params['limit'] = (int)input('limit', 10);
            $params['page']  = (int)input('page', 1);
            $params['first'] = ($params['page'] - 1) * $params['limit'];
            $params['field'] = input('field', 'id');
            $params['order'] = input('order', 'asc');
            $data            = ModelsModel::getModelList($params);
            $this->success('ok', $data['list'], $data['count']);
        }

        return View::fetch();
    }

    /**
     * 添加内容模型
     * @return string
     * @throws \think\db\exception\DbException
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = self::input();
            if (empty($param['name'])) {
                $this->error('模型名称不能为空');
            }
            if (empty($param['alias'])) {
                $this->error('模型别名不能为空');
            }
            if (empty($param['type'])) {
                $this->error('类型不能为空');
            }
            if (empty($param['index_tpl'])) {
                $this->error('栏目模板不能为空');
            } else {
                $param['index_tpl'] = explode('.', $param['index_tpl'])[0];
            }

            if (empty($param['list_tpl'])) {
                $this->error('列表模板不能为空');
            } else {
                $param['list_tpl'] = explode('.', $param['list_tpl'])[0];
            }
            if (empty($param['show_tpl'])) {
                $this->error('内容模板不能为空');
            } else {
                $param['show_tpl'] = explode('.', $param['show_tpl'])[0];
            }

            //判断别名是否存在
            $isAlias = ModelsModel::where('alias', $param['alias'])->count();
            if ($isAlias) {
                $this->error('该别名已存在,不允许重名');
            }
            $param['create_time'] = time();
            $param['update_time'] = time();
            ModelsModel::strict(false)->insert($param);
            $this->success('操作成功');
        }

        return View::fetch();
    }

    /**
     * 修改内容模型
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            //获取序列化数据
            $param = self::input();
            if (empty($param['id'])) {
                $this->error('参数错误');
            }
            //赋值tablename
            ModelsModel::update($param, ['id' => $param['id']]);
            $this->success('操作成功');
        }
        $id                = input('get.id');
        $data              = ModelsModel::find($id);
        $data['index_tpl'] = $data['index_tpl'] ? $data['index_tpl'].'.html' : '';
        $data['list_tpl']  = $data['list_tpl'] ? $data['list_tpl'].'.html' : '';
        $data['show_tpl']  = $data['show_tpl'] ? $data['show_tpl'].'.html' : '';
        View::assign('data', $data);

        return View::fetch();
    }

    /**
     * 修改内容模型
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function modify()
    {
        if ($this->request->isAjax()) {
            if (empty(input('get.id')) || empty(input('get.field'))) {
                $this->error('参数错误');
            }
            $param[input('get.field')] = input('val');
            $param['id']               = input('get.id');
            ModelsModel::update($param, ['id' => $param['id']]);
            $this->success('操作成功');
        }
    }

    /**
     * 删除内容模型
     * @return void
     */
    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = (int)input('post.id');
            if (empty($id)) {
                $this->error("参数错误");
            }
            ModelsModel::where(['id' => $id])->delete();
            $this->success("删除成功");
        }
    }

    /**
     * 模型导入
     */
    public function import(){

    }

    /**
     * 模型导出
     */
    public function export()
    {
        $id  = $this->request->param('id');
        $row = ModelsModel::find($id);
        if ( ! $row) {
            $this->error("没有找到数据");
        }
        $modelField = Db::name('models_field')->where(['model_id' => $id])->select()->toArray();
        $data       = [];
        foreach ($modelField as $key => &$value) {
            unset($value['id']);
        }
        $data['model'] = $row->toArray();
        unset($data['model']['id']);
        $data['model_field'] = $modelField;

        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=model_".$row->name.$id.'.txt');
        die(base64_encode(json_encode($data)));
    }

}
